package zmee.pmct.opplugin;

import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.dataentity.entity.DynamicObjectCollection;
import kd.bos.dataentity.utils.ObjectUtils;
import kd.bos.entity.plugin.AbstractOperationServicePlugIn;
import kd.bos.entity.plugin.PreparePropertysEventArgs;
import kd.bos.entity.plugin.args.BeforeOperationArgs;
import kd.bos.orm.query.QCP;
import kd.bos.orm.query.QFilter;
import kd.bos.servicehelper.BusinessDataServiceHelper;
import kd.bos.servicehelper.QueryServiceHelper;
import zmee.pmct.pojo.SubListPojo;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

public class BeforeSaveFkdjdOp extends AbstractOperationServicePlugIn {
    @Override
    public void onPreparePropertys(PreparePropertysEventArgs e) {
//        e.getFieldKeys().add("entryentity.subentryentity");
//        e.getFieldKeys().add("entryentity.subentryentity.budgetitem");
//        e.getFieldKeys().add("entryentity.subentryentity.contractamount");
//        e.getFieldKeys().add("entryentity.subentryentity.actualpayamt");
    }

    @Override
    public void beforeExecuteOperationTransaction(BeforeOperationArgs e) {
        DynamicObject[] dataEntities = e.getDataEntities();
        for (DynamicObject dataEntity : dataEntities) {
            Date bizdate = dataEntity.getDate("bizdate");
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMM");
            String format = simpleDateFormat.format(bizdate);
            DynamicObject period = BusinessDataServiceHelper.loadSingle("bd_period", "id", new QFilter[]{new QFilter("number", QCP.equals, format)});
            dataEntity.set("period",period);//期间
            DynamicObjectCollection entryentity = dataEntity.getDynamicObjectCollection("entryentity");//付款信息分录
            for (DynamicObject dynamicObject : entryentity) {//付款信息分录
                DynamicObjectCollection subentryentity = dynamicObject.getDynamicObjectCollection("subentryentity");//付款分摊分录
                subentryentity.clear();
                DynamicObject entrycontract = dynamicObject.getDynamicObject("entrycontract");//合同
//                BigDecimal subPreapplyoftaxamtsum = dynamicObject.getBigDecimal("preapplyoftaxamtsum");//付款信息——本期申请金额;//减少后的本次申请金额
                BigDecimal subPreapplyoftaxamtsum = dynamicObject.getBigDecimal("thispaymentoftaxamount");//付款信息——本次实付含税总金额;//减少后的本次申请金额
                if (!ObjectUtils.isEmpty(entrycontract)){
                    DynamicObject project = entrycontract.getDynamicObject("project");//项目
                    DynamicObject partb = entrycontract.getDynamicObject("partb");//合同乙方——供应商
                    dynamicObject.set("contpro",project);
                    dynamicObject.set("contpartb",partb);
                    entrycontract = BusinessDataServiceHelper.loadSingle(entrycontract.getPkValue(), "pmct_outcontract");
                    //根据合同查询合同清单分录数据对应生产付款分摊分录
                    DynamicObjectCollection listmodelentries = entrycontract.getDynamicObjectCollection("listmodelentry");//清单模板分录

                    for (DynamicObject listmodelentry : listmodelentries) {
                        DynamicObjectCollection treelistentry = listmodelentry.getDynamicObjectCollection("sublistentry");//合同清单
                        //判断合同清单预算项要分组
                        ArrayList<SubListPojo> subListPojos = new ArrayList<>();
                        for (DynamicObject treelist : treelistentry) {
                            SubListPojo subListPojo = new SubListPojo();
                            subListPojo.setYsx(treelist.getDynamicObject("listingbudgetitem").getPkValue().toString());
                            subListPojo.setOftax(treelist.getBigDecimal("oftax"));
                            subListPojos.add(subListPojo);
                        }
                        Map<String, List<SubListPojo>> collect = subListPojos.stream().collect(Collectors.groupingBy(SubListPojo::getYsx, Collectors.toList()));
                        Map<String,SubListPojo> result = new HashMap<>();
                        for (String object : collect.keySet()) {
                            result.put(object,
                                    collect.get(object).stream().reduce((a,b)->
                                            new SubListPojo(
                                                    a.getYsx(),
                                                    a.getOftax().add(b.getOftax())
                                            )).get()
                            );
                        }
                        Iterator<String> iterator = result.keySet().iterator();
                        while (iterator.hasNext()){
                            String key = iterator.next();
                            SubListPojo subListPojo = result.get(key);
                            BigDecimal amount=subListPojo.getOftax();//金额
//                            DynamicObject listingbudgetitem = treelist.getDynamicObject("listingbudgetitem");//预算项

                            BigDecimal sfje = new BigDecimal(0);
                            //根据预算项在星瀚根据预算项检索pmbs_contractbudget  合同预算项执行详情 ，取单据里有 实收实付申请（已审核）（项目币）actualauditamt
//                            BigDecimal amount = treelist.getBigDecimal("oftax");
                            DynamicObject contractbudget = QueryServiceHelper.queryOne("pmbs_contractbudget", "actualauditamt",
                                    new QFilter[]{new QFilter("budgetitem", QCP.equals, key)
                                            .and("contract",QCP.equals,entrycontract.getPkValue())});
                            if (!ObjectUtils.isEmpty(contractbudget)){
                                sfje = (BigDecimal) contractbudget.get(0);//实付金额
                            }
                            DynamicObject subentry = subentryentity.addNew();
                            subentry.set("budgetitem",new Long(key));//付款分摊分录——预算项
                            subentry.set("contractamount",amount);//付款分摊分录——合同金额
                            subentry.set("actualpayamt",sfje);//付款分摊分录——实付金额
                            //获取本次实付分摊金额  （付款分摊_合同金额）—(付款分摊_实付金额) 且小于 付款信息的本次实付含税总金额
                            BigDecimal subtract = amount.subtract(sfje);// 本次实付分摊金额
                            //判断本次实付分摊金额是否小于已扣的 付款信息_本次申请金额
                            if (subtract.compareTo(subPreapplyoftaxamtsum)<=0){
                                if (!iterator.hasNext()){
                                    //如果是最后一次循环本次实付分摊金额=（累减的）本次实付含税总金额
                                    subtract=subPreapplyoftaxamtsum;
                                }
                                subentry.set("curactualpaysplitamt",subtract);//付款分摊_本次实付分摊金额
                                subentry.set("totalactualpayamt",subtract.add(sfje));//付款分摊_累计实付金额
                                subPreapplyoftaxamtsum = subPreapplyoftaxamtsum.subtract(subtract);//减少后的本次申请金额
                            }else {
//                                BigDecimal lastSubtract = subtract.subtract(subPreapplyoftaxamtsum);
                                subtract=subPreapplyoftaxamtsum;
                                subentry.set("curactualpaysplitamt",subtract);//付款分摊_本次实付分摊金额
                                subentry.set("totalactualpayamt",subPreapplyoftaxamtsum.add(sfje));//付款分摊_累计实付金额
                                subPreapplyoftaxamtsum = subPreapplyoftaxamtsum.subtract(subtract);//减少后的本次申请金额
                            }



                        }

//                        for (DynamicObject treelist : treelistentry) {
//                            DynamicObject listingbudgetitem = treelist.getDynamicObject("listingbudgetitem");//预算项
//
//                            BigDecimal sfje = new BigDecimal(0);
//                            //根据预算项在星瀚根据预算项检索pmbs_contractbudget  合同预算项执行详情 ，取单据里有 实收实付申请（已审核）（项目币）actualauditamt
//                            BigDecimal amount = treelist.getBigDecimal("oftax");//金额
//                            DynamicObject contractbudget = QueryServiceHelper.queryOne("pmbs_contractbudget", "actualauditamt",
//                                    new QFilter[]{new QFilter("budgetitem", QCP.equals, listingbudgetitem.getPkValue())
//                                            .and("contract",QCP.equals,entrycontract.getPkValue())});
//                            if (!ObjectUtils.isEmpty(contractbudget)){
//                                sfje = (BigDecimal) contractbudget.get(0);//实付金额
//                            }
//                            DynamicObject subentry = subentryentity.addNew();
//                            subentry.set("budgetitem",listingbudgetitem);//付款分摊分录——预算项
//                            subentry.set("contractamount",amount);//付款分摊分录——合同金额
//                            subentry.set("actualpayamt",sfje);//付款分摊分录——实付金额
//                            //获取本次实付分摊金额  （付款分摊_合同金额）—(付款分摊_实付金额) 且小于 付款信息的本次实付含税总金额
//                            BigDecimal subtract = amount.subtract(sfje);// 本次实付分摊金额
//                            //判断本次实付分摊金额是否小于已扣的 付款信息_本次申请金额
//                            if (subtract.compareTo(subPreapplyoftaxamtsum)<=0){
//                                subentry.set("curactualpaysplitamt",subtract);//付款分摊_本次实付分摊金额
//                                subentry.set("totalactualpayamt",subtract.add(sfje));//付款分摊_累计实付金额
//                                subPreapplyoftaxamtsum = subPreapplyoftaxamtsum.subtract(subtract);//减少后的本次申请金额
//                            }else {
////                                BigDecimal lastSubtract = subtract.subtract(subPreapplyoftaxamtsum);
//                                subtract=subPreapplyoftaxamtsum;
//                                subentry.set("curactualpaysplitamt",subtract);//付款分摊_本次实付分摊金额
//                                subentry.set("totalactualpayamt",subPreapplyoftaxamtsum.add(sfje));//付款分摊_累计实付金额
//                                subPreapplyoftaxamtsum = subPreapplyoftaxamtsum.subtract(subtract);//减少后的本次申请金额
//                            }
//                        }
                    }
                }




            }
        }

    }
}
